package com.hhxyjsj;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;
import org.dom4j.Element;

import com.hhxyjsj.model.PassengerInfo;
import com.hhxyjsj.model.TrainNumberInfo;
import com.hhxyjsj.util.VClient;



public class OrderTicket {
	private VClient client = null;
	
	private final static String domain = "https://dynamic.12306.cn";
	
	public OrderTicket(){
		client =new VClient("utf-8");
		client.setClientIsNotSafe();
	}
	
	/**
	 * 登陆系统
	 * @param userName 登陆的用户名
	 * @param password 登陆的密码
	 * @param fullName 注册的中文件名称
	 * @return
	 */
	private boolean login(String userName,String password,String fullName){
		FileOutputStream fos = null;
		String img_rrand_code = "";
		BufferedReader br = null;
		try{
			String img_rrand_code_src = "/otsweb/passCodeAction.do?rand=lrand";	
			client.doGet(domain + img_rrand_code_src, null);
			fos = new FileOutputStream("c:/img_rrand_code_src.jpg");
			IOUtils.copy(client.getInputStream(),fos );
			fos.close();
			fos = null;
			br = new BufferedReader(new InputStreamReader(System.in));
			while(true){
				System.out.print("请输入登陆时的验证码:");
				img_rrand_code = br.readLine();
				if(img_rrand_code != null && !"".equals(img_rrand_code)){
					break;
				}
			}
//			img_rrand_code =(String)IOUtils.readLines(new FileReader("c:/img_rrand_code.txt")).get(0);
		}catch(IOException e){
			e.printStackTrace();
			return false;
		}finally{			
			try {
				if(fos != null){
					fos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		if(img_rrand_code == null || "".equals(img_rrand_code)){
			System.out.println("验证码为空!");
			return false;
		}
		//登陆链接
		String loginForm_action="https://dynamic.12306.cn/otsweb/loginAction.do?method=login";
		Map params=new HashMap();
		params.put("loginUser.user_name", userName);
		params.put("user.password", password);
//		System.out.println("-------"+img_rrand_code);
//		params.put("randCode", img_rrand_code);
		//登陆系统
		client.doPost(loginForm_action, params);
	
		//查看个人信息
		client.doPost("https://dynamic.12306.cn/otsweb/sysuser/user_info.jsp", null);
		
		String content = client.getContent();
		if(content.indexOf(fullName) == -1){
			return false;
		}
		return true;
	}
	
	private String queryTicket(TrainNumberInfo tni){
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		Map params = new HashMap();
		//预定
		params.clear();
		params.put("from_station_telecode",tni.getFromStationTelecode());
		params.put("from_station_telecode_name",tni.getFromStationName());
		params.put("include_student","00");
		//历时
		params.put("lishi",tni.getLishi());//....
		//TODO 参数意义未知
		params.put("round_start_time_str",tni.getRoundStartTimeStr());
		params.put("round_train_date",sdf.format(new Date(System.currentTimeMillis())));//查询时间...
		params.put("seattype_num","");
		params.put("single_round_type","1");
		//TODO 参数意义未知
		params.put("start_time_str",tni.getRoundStartTimeStr());
		params.put("station_train_code",tni.getStationTrainCode());
		params.put("to_station_telecode",tni.getToStationTelecode());
		params.put("to_station_telecode_name",tni.getToStationName());
		//?
		params.put("train_class_arr","QB#D#Z#T#K#QT#");//...
		params.put("train_date",tni.getTrainDate());//发车时间...
		params.put("arrive_time",tni.getEndTime());//到达时间
		//?
		params.put("train_pass_type","QB");
		params.put("train_start_time",tni.getStartTime());//发出时间	
		//该参数的值固定
		params.put("ypInfoDetail","1021500232303770000040600000001021503310");

		client.doPost("https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=submutOrderRequest", params);
		String content = client.getContent();
		System.out.println(client.getContent());
		String token = "";
		String str = "<div><input type=\"hidden\" name=\"org.apache.struts.taglib.html.TOKEN\" value=\"";
		int index;
		if((index = content.indexOf(str)) != -1){
			content = content.substring(index + str.length());
			token = content.substring(0, content.indexOf("\""));
		}
		return token;
	}
	
	private boolean submitOrder(TrainNumberInfo tni,List<PassengerInfo>  piList){
		Map params = new HashMap();
		params.put("checkbox0", "0");
		params.put("checkbox1", "1");

		/*params.put("checkbox9","Y");//保存到常用联系人
		params.put("checkbox9","Y");
		params.put("checkbox9","Y");
		params.put("checkbox9","Y");*/
		List vList = new ArrayList();
		vList.add("Y");
		vList.add("Y");
		vList.add("Y");
		vList.add("Y");
		params.put("checkbox9", vList);
		
	/*	params.put("oldPassengers","");
		params.put("oldPassengers","");
		params.put("oldPassengers","");
		params.put("oldPassengers","");
		params.put("oldPassengers","");*/
		vList.clear();
		vList.add("舒二毛,1,431223198602283013");
		vList.add("米建梅,1,431221198601152027");
		vList.add("");
		vList.add("");
		params.put("oldPassengers", vList);


		//该参数的值固定
		params.put("orderRequest.bed_level_order_num","000000000000000000000000000000");
		params.put("orderRequest.cancel_flag","1");
		params.put("orderRequest.end_time",tni.getEndTime());//到达时间
		params.put("orderRequest.from_station_name",tni.getFromStationName());//出发地
		params.put("orderRequest.from_station_telecode",tni.getFromStationTelecode());
		params.put("orderRequest.id_mode","Y");

		
		params.put("orderRequest.seat_type_code","");
		params.put("orderRequest.start_time",tni.getStartTime());//发车时间
		params.put("orderRequest.station_train_code",tni.getTrainNo());//车次
		params.put("orderRequest.ticket_type_order_num","");
		params.put("orderRequest.to_station_name",tni.getToStationName());
		params.put("orderRequest.to_station_telecode",tni.getToStationTelecode());
		params.put("orderRequest.train_date",tni.getTrainDate());//发车时间
		params.put("orderRequest.train_no",tni.getTrainNo());//车号
		
		int i = 1;
		vList.clear();
		for(PassengerInfo pi : piList){
			params.put("org.apache.struts.taglib.html.TOKEN",pi.getToken());// ...
			/*选择支付方式:
			 *A 网上支付<span>须在规定时间内完成支付，快捷进站乘车
			 *B 网上预订<span>须在规定时间内取票，否则铁路将不予以保留席位
			 */
			params.put("orderRequest.reserve_flag",pi.getReserveFlag());
			
			//乘客信息，多个人时参数自动编号passenger_1_cardno,passenger_2_cardno
			params.put("passenger_" + i + "_cardno",pi.getCardNo());//身份证号码
			params.put("passenger_" + i + "_cardtype",pi.getCardType());//证件类型
			params.put("passenger_" + i + "_mobileno",pi.getMobileNo());
			params.put("passenger_" + i + "_name",pi.getpassengerName());
			/*
			 * 坐位类型
			 * 3 硬卧,1 硬座,4 软卧
			 */
			params.put("passenger_" + i + "_seat",pi.getSeatType());
			//车票类型
			// 1 成人票,2 儿童票 3 学生票 4 残军票
			params.put("passenger_" + i + "_ticket",pi.getTicketType());
			
			//多人时，重复该参数...
//			params.put("passengerTickets",pi.getPassengerTickets());//车票信息
			vList.add(pi.getPassengerTickets());
			i++;
		}				
		params.put("passengerTickets",vList);
		params.put("textfield","中文或拼音首字母");	
		
		client.doPost(domain + "/otsweb/passCodeAction.do?rand=randp", null);
		FileOutputStream fos = null;
		String randCode = "";
		BufferedReader br = null;
		try{
			fos = new FileOutputStream("c:/img_rrand_code_src1.jpg");
			IOUtils.copy(client.getInputStream(),fos);	
			fos.close();
			fos = null;
			br = new BufferedReader(new InputStreamReader(System.in));
			while(true){
				System.out.print("请输入提交定单的验证码:");
				randCode = br.readLine();
				if(randCode != null && !"".equals(randCode)){
					break;
				}
			}
//			randCode = (String)IOUtils.readLines(new FileReader("c:/img_rrand_code.txt")).get(0);
		}catch(Exception e){
			e.printStackTrace();
		} finally{
			try {
				if(fos != null){				
					fos.close();
				}
				if(br != null){
					br.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		params.put("randCode",randCode);//验证码	

		client.doPost(domain + "/otsweb/order/confirmPassengerAction.do?method=confirmPassengerInfoSingle", params);
	    System.out.println("...提交定单的返回信息...");
		System.out.println(client.getContent());
		System.out.println(".....................");
		return true;
	}
	
	public boolean orderTicket(String userName,String password,String fullName){
		//K267#1612#12:10#240000K2670V#BXP#HHQ 到达时间:15:02 历时26:52 
		//T61#1337#16:37#2400000T610L#BXP#HHQ 到达时间14:54 历时22:17 
		//T87#1349#15:58#2400000T870C#BXP#HHQ 到达时间14:27 历时22:29 

		
		//K267
		TrainNumberInfo tnf = new TrainNumberInfo(
				"K267","240000K2670V",
				"BXP","北京西", 
				"HHQ","怀化", 
				"2012-01-13","12:10",
				"15:02","00:00--24:00", 
				"26:52","",
				"");
		//T61#1337#16:37#2400000T610L#BXP#HHQ 到达时间14:54 历时22:17 
		/*TrainNumberInfo tnf = new TrainNumberInfo(
				"T61","2400000T610L",
				"BXP","北京西", 
				"HHQ","怀化", 
				"2012-01-13","16:37",
				"14:54","00:00--24:00", 
				"22:17","",
				"");*/
		
		boolean success = login(userName, password, fullName);
		if(success){
			System.out.println("...已成功登陆系统...");
			while(true){
				String token = queryTicket(tnf);
				if(token != null && !"".equals(token)){
					List<PassengerInfo> piList = new ArrayList<PassengerInfo>();
					PassengerInfo pi = new PassengerInfo(
							"舒二毛", "13520791933",
							"1", "431223198602283013", 
							"1", "A", 
							"1", token);
					piList.add(pi);
					
					System.out.println("...有票,填写定单信息...");
					success = submitOrder(tnf,piList);
					if(success){
						System.out.println("...定票成功...");
						break;
					}
				}
				try {
					Thread.sleep(30000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}else{
			System.out.println("...登陆失败...");
		}
		return true;
	}
	
	public static void main(String[] agrs){
		OrderTicket ticket = new OrderTicket();
		String userName = "hhxyjsj";
		String password = "860115";
		String fullName = "舒二毛";
		
		/*String userName = "jettech_mijm";
		String password = "860115";
		String fullName = "米建梅";*/
		
		ticket.orderTicket(userName, password, fullName);
	}
}
